

import 'package:animated_search_bar/animated_search_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/indent/iview/indent_search_list_iview.dart';
import 'package:flutter_deer/indent/page/indent_search_list_page.dart';
import 'package:flutter_deer/indent/presenter/indent_search_list_presenter.dart';
import 'package:flutter_deer/indent/provider/indent_search_list_provider.dart';
import 'package:flutter_deer/index/models/user_betting_entity.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class IndentSearchPage extends StatefulWidget {

  const IndentSearchPage({super.key});

  @override
  _IndentSearchPageState createState() => _IndentSearchPageState();
}

class _IndentSearchPageState extends State<IndentSearchPage> with SingleTickerProviderStateMixin,BasePageMixin<IndentSearchPage, PowerPresenter>, AutomaticKeepAliveClientMixin implements IndentSearchListIMvpView{

  TabController? _tabController;
  final PageController _pageController = PageController();
  IndentSearchListProvider listProvider = IndentSearchListProvider();
  final GlobalKey _bodyKey = GlobalKey();
  late IndentSearchListPresenter indentSearchListPresenter;
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    indentSearchListPresenter = new IndentSearchListPresenter();
    powerPresenter.requestPresenter([indentSearchListPresenter]);
    return powerPresenter;
  }

  @override
  void setSearchResult(UserBettingSearchEntity? result){
    listProvider.setSearchResult(result);
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
  }

  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final Color? iconColor = ThemeUtils.getIconColor(context);
    double textWidth = 0;
    List<String> titles = [DeerLocalizations.of(context)!.waitLottery.nullSafe,DeerLocalizations.of(context)!.winLottery.nullSafe,DeerLocalizations.of(context)!.lossLottery.nullSafe];
    for(int i=0;i<titles.length;i++){
      TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: titles.elementAt(i),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      if(textWidth<textPainter.size.width){
        textWidth = textPainter.size.width;
      }
    }
    return ChangeNotifierProvider<IndentSearchListProvider>(
        create: (_) => listProvider,
        child:  Consumer<IndentSearchListProvider>(
        builder: (_,provider,child)
    {
      return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              onPressed: () async {
                FocusManager.instance.primaryFocus?.unfocus();
                final isBack = await Navigator.maybePop(context);
                if (!isBack) {
                  await SystemNavigator.pop();
                }
              },
              tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
              padding: EdgeInsets.all(12.0),
              icon: Image.asset(
                Constant.backImg,
                color: ThemeUtils.getIconColor(context),
                height: 24,
                width: 24,
              ),
            ),
            title: AnimatedSearchBar(
                label: '${DeerLocalizations.of(context)!.inputName.nullSafe}',
                controller: _controller,
                searchIcon: LoadAssetImage(
                  'goods/search',
                  key: const Key('searchIcon'),
                  width: 24.0,
                  height: 24.0,
                  color: iconColor,
                ),
                closeIcon: LoadAssetImage(
                  'goods/search',
                  key: const Key('closeIcon'),
                  width: 24.0,
                  height: 24.0,
                  color: iconColor,
                ),
                labelStyle: TextStyle(fontSize: 16,color: context.isDark ? Colours.text_gray : Colours.text,),
                searchStyle: TextStyle(color: context.isDark ? Colours.text_gray : Colours.text,),
                cursorColor: context.isDark ? Colours.text_gray : Colours.text,
                textInputAction: TextInputAction.done,
                searchDecoration: InputDecoration(
                  hintText: '${DeerLocalizations.of(context)!.search.nullSafe}',
                  alignLabelWithHint: true,
                  fillColor: Colors.white,
                  focusColor: Colors.white,
                  hintStyle: TextStyle(color: context.isDark ? Colours.text_gray : Colours.text,),
                  border: InputBorder.none,
                ),
                onFieldSubmitted: (value){
                  listProvider.setLoading();
                  indentSearchListPresenter.search(value);
                }
            ),
          ),
          body: Column(
              key: _bodyKey,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  // 隐藏点击效果
                  padding: const EdgeInsets.only(left: 0.0,right: 0.0),
                  color: context.backgroundColor,
                  child: TabBar(
                    onTap: (index) {
                      if (!mounted) {
                        return;
                      }
                      _pageController.jumpToPage(index);
                    },
                    isScrollable: true,
                    controller: _tabController,
                    labelStyle: TextStyles.textBold18,
                    indicatorSize: TabBarIndicatorSize.label,
                    labelPadding: EdgeInsets.zero,
                    unselectedLabelColor: context.isDark ? Colours.text_gray : Colours.text,
                    labelColor: Theme.of(context).primaryColor,
                    indicatorPadding: const EdgeInsets.only(right: 18,left: 18),
                    tabs: <Widget>[
                      _TabView('${DeerLocalizations.of(context)!.waitLottery.nullSafe}', 0,textWidth),
                      _TabView('${DeerLocalizations.of(context)!.winLottery.nullSafe}', 1,textWidth),
                      _TabView('${DeerLocalizations.of(context)!.lossLottery.nullSafe}', 2,textWidth)
                      // _TabView('已撤销', 3)
                    ],
                  ),
                ),
                Gaps.line,
                Expanded(
                    child: PageView.builder(
                        key: const Key('pageView'),
                        itemCount: 3,
                        onPageChanged: _onPageChange,
                        controller: _pageController,
                        itemBuilder: (_, int index) {
                          if(index==0){
                            return IndentSearchListPage(list: listProvider.waitList??[],);
                          }else if(index==1){
                            return IndentSearchListPage(list: listProvider.winList??[],);
                          }else if(index==2){
                            return IndentSearchListPage(list: listProvider.lossList??[],);
                          }else{
                            return IndentSearchListPage(list: [],);
                          }
                        }
                    )
                )
              ]
          )
      );
    }));
  }

  void _onPageChange(int index) {
    _tabController?.animateTo(index);
    listProvider.setIndex(index);
    _pageController.jumpToPage(index);
  }

  @override
  bool get wantKeepAlive => false;
}

class _TabView extends StatelessWidget {

  const _TabView(this.tabName, this.index,this.maxLabelWidth);

  final String tabName;
  final int index;
  final double maxLabelWidth;

  @override
  Widget build(BuildContext context) {
    if(maxLabelWidth>MediaQuery.of(context).size.width/3-66) {
      return Tab(
          child: Padding(padding: EdgeInsets.only(left: 10, right: 10),
            child: Text(tabName),
          )
      );
    }else{
      return Tab(
        child: SizedBox(
          width: MediaQuery.of(context).size.width/3-36,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(tabName)
            ],
          ),
        ),
      );
    }
  }
}
